package com.xunmall.wechat.service.impl;

import com.xunmall.wechat.model.AccessToken;
import com.xunmall.wechat.model.JsSdkTicket;
import com.xunmall.wechat.model.WeChatUserInfo;
import com.xunmall.wechat.util.wechat.WeChatGlobalUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class WeChatService {

    @Async
    public String getQRCode(String accessToken, String opendId, String parentOpenid) {
        // 根据token和opendId拉取用户个人信息
        WeChatUserInfo userInfo = WeChatGlobalUtils.getUserInfo(accessToken, opendId);
        // 获取带参数的二维码所需要的ticket
        String ticket = WeChatGlobalUtils.createLongTicket(accessToken, userInfo.getNickname() + ";" + userInfo.getOpenid());
        //根据ticket获取二维码地址
        String qrcodeUrl = WeChatGlobalUtils.showQrcode(ticket);
        //信息入库
        userInfo.setQrcode_url(qrcodeUrl);
        userInfo.setParent_openId(parentOpenid);
        //todo 可以将关注后的数据信息做入库操作
        System.out.println(userInfo);
        return null;
    }


    @Cacheable(value = "access_token", key = "#root.targetClass.simpleName + ':' + #root.methodName  + #appId")
    public AccessToken getGlobalAccessToken(String appId, String appSecret) {
        System.out.println("token from wechat");
        AccessToken accessToken = WeChatGlobalUtils.getAccessToken(appId, appSecret);
        if (accessToken == null) {
            return null;
        }
        return accessToken;
    }

    @Cacheable(value = "js_ticket", key = "#root.targetClass.simpleName + ':' + #root.methodName + #accessToken ")
    public JsSdkTicket getGlobalJsSdkTicket(String accessToken) {
        System.out.println("ticket from wechat");
        JsSdkTicket jsSdkTicket = WeChatGlobalUtils.getJSTicket(accessToken);
        if (jsSdkTicket == null) {
            return null;
        }
        return jsSdkTicket;
    }

}
